package utils

import (
	"io"
	"os"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func InitLogger(level zapcore.Level, logFilePath string, isDevMode bool) *zap.SugaredLogger {
	encoder := getEncoder()
	writeSyncer := getLogWriter(logFilePath, isDevMode)
	core := zapcore.NewCore(encoder, writeSyncer, level)
	// zap.AddCaller()  添加将调用函数信息记录到日志中的功能。
	return zap.New(core, zap.AddCaller()).Sugar()
}

func getEncoder() zapcore.Encoder {
	// encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig := zap.NewDevelopmentEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder // 修改时间编码器

	// 在日志文件中使用大写字母记录日志级别
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	// NewConsoleEncoder 打印更符合人们观察的方式
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter(logFilePath string, isDevMode bool) zapcore.WriteSyncer {
	var logger io.Writer
	if isDevMode {
		// 开发模式下，日志直接输出到控制台，方便开发者查看和调试
		logger = os.Stdout
	} else {
		logger = &lumberjack.Logger{
			Filename:   logFilePath,
			MaxSize:    10,
			MaxBackups: 5,
			MaxAge:     30,
			Compress:   false,
		}
	}
	return zapcore.AddSync(logger)
}
